(function(){
	var scale = 'medium';
    if(deviceType == 'mobile'){
        scale = 'large';
    }
	Ext.override(Ext.Button, {
		scale: scale
	});

    var prevOnRefresh = Ext.grid.RowSelectionModel.prototype.onRefresh;

    Ext.override(Ext.grid.RowSelectionModel,{
        // TODO (nmatei) request better solution from extjs to implement fixes
        initEvents: Ext.grid.RowSelectionModel.prototype.initEvents.createSequence(function(){
            this.on({
                beforerowselect: function(){
                    this.selectionChange = true;
                },
                rowdeselect: function(sm, index, r){
                    if (!this.selectionChange){
                        //console.debug('CLEAR');
                        this.fireEvent('clearselection', sm, index, r); // new event - selection lost
                        if(!sm.hasSelection()){
                            this.fireEvent('clearselections', sm, index, r); // new event - no selections
                        }
                    }
                },
                rowselect: function(){
                    delete this.selectionChange;
                    //console.debug('ROW SELECT');
                }
            })
        }),

        // private
        onRemove : function(v, index, r){ // TODO verify original code after upgrade extjs
            var me = this;
            if(me.selections.remove(r) !== false){
                me.fireEvent('selectionchange', me);
                me.fireEvent('clearselection', me, index, r); // new event - selection lost
                if(!me.hasSelection()){
                    me.fireEvent('clearselections', me, index, r); // new event - no selections
                }
            }
        },
        
        // private
        onRefresh : function(){
            var me = this,
                s = me.hasSelection(),
                r = me.getSelections();
            prevOnRefresh.apply(me, arguments); // call original
            if(s && !me.hasSelection()){
                //var ds = me.grid.store;
                me.fireEvent('clearselections', me, -1, r[0]); // new event
            }
        }
    });
    
    /**
     * @class Ext.form.TextField 
     */
    var originalSetValue = Ext.form.TextField.prototype.setValue,
        originalGetValue = Ext.form.TextField.prototype.getValue;

    Ext.override(Ext.form.TextField, {
//        validationDelay: 1000,

        /**
         * @cfg {String} useTrim Specify <tt>false</tt> to allow start OR end spaces and not trim original value
         * (defaults to <tt>true</tt>). <tt>Ext.util.Format.trim</tt> before get/set value.
         * The supported values are <tt>true</tt>, <tt>false</tt>.
         */
        useTrim : true,

        setValue : function(v){
            if(this.useTrim){
                v = Ext.util.Format.trim(v);
            }
            originalSetValue.call(this, v);
            return this;
        },

        getValue : function(){
            var v = originalGetValue.call(this);
            if(this.useTrim){
                v = Ext.util.Format.trim(v);
            }
            return v;
        }
    });

    /**
     * @class Ext.Component
     */
    // TODO (nmatei) hack for bug: initial disabled bug in IE
    // http://www.sencha.com/forum/showthread.php?104990-FormPanel-Panel-initial-disabled-in-hbox-mask-amp-position-bug&p=492028
    if(Ext.isIE){
        Ext.override(Ext.Component, {
            render : Ext.Component.prototype.render.createSequence(function(){
                if(this.disabled){
                    (function(){
                        // pass silent so the event doesn't fire the first time.
                        if (this.disabled){ // this.disabled could be changed in the meantime
                            this.disable(true);
                        }
                    }).defer(1, this); // like java Thread.yield :)
                }
            })
        });
    }

	Ext.override(Ext.form.ComboBox, {
		postBlur: Ext.form.ComboBox.prototype.postBlur.createSequence(function(){
			if(this.editable && this.clearFilterOnReset && this.mode == 'local'){
				console.debug('ComboBox.postBlur -> store.clearFilter');
				this.store.clearFilter();
			}
		})
	});


    Ext.override(Ext.ux.form.SearchField, {
        minChars: 3,
		
		keyupTaskDelay: 300,

        initEvents : Ext.ux.form.SearchField.prototype.initEvents.createSequence(function(){
            var me = this;
            if(me.onKeyup) {
                me.el.on('keyup', me.onKeyupAction, me);
            }
        }),
		
		// private
		onKeyupAction: function(){
			var me = this;
			if (!me.searchTask) {
				me.searchTask = new Ext.util.DelayedTask(me.onTrigger2Click, me);
			}
			me.searchTask.delay(me.keyupTaskDelay);
		},
		
		onTrigger1Click : function(){
			var me = this;
			if(me.hasSearch){
				me.el.dom.value = '';
				var o = {start: 0},
					store = me.store;
				store.baseParams = store.baseParams || {};
				store.baseParams[me.paramName] = '';
				store.removeAll();
				me.triggers[0].hide();
				me.hasSearch = false;
			}
		},

        onTrigger2Click : function(){
            var me = this,
                v = me.getRawValue();
			me.highlightsTerms = [];
            if(v.length < me.minChars){
                //me.onTrigger1Click();
                return;
            }
			// matei add
			var split = me.store.baseParams.type != 'text',
			    highlights = Ext.util.Terminology.createHighlightsTerms(v, me.minChars, split);
			me.highlightsTerms = highlights.terms;
			
            var o = {start: 0};
            me.store.baseParams = me.store.baseParams || {};
            me.store.baseParams[me.paramName] = v;
            me.store.reload({params:o});
            me.hasSearch = true;
            me.triggers[0].show();
        }
    });

})();


Ext.override(Ext.Window, {
    constrain: true
//    initEvents: Ext.Window.prototype.initEvents.createSequence(function(){
//        if(this.resizable && this.constrain){
//            this.resizer.constrainTo = this.container;
//        }
//    })
});


(function(){
    Ext.QuickTip.prototype.tagConfig.url = 'qurl';

	Ext.override(Ext.QuickTip, {
        // private
        urlBodyUpdate: function(t){
            var u,
                url,
                et = Ext.fly(t.el),
                cfg = this.tagConfig,
                ns = cfg.namespace;
            url = et.getAttribute(cfg.url, ns);
            if(url){
                u = this.body.getUpdater();
                u.update({
                    scope: this,
                    url: url,
                    callback: function(el, success, response, options){
                        if(success && (et = Ext.fly(t.el))){
                            // found the element again, is changed when move fast through elements
                            var o = {};
                            o[ns+':'+cfg.attribute] = response.responseText; // set
                            o[ns+':'+cfg.url] = ''; // remove qurl to not be loaded many times
                            et.set(o);
                            if(!t.width){
                                this.doAutoWidth();
                            }
                        }
                    }
                });
            }
        },

        showAt: Ext.QuickTip.prototype.showAt.createSequence(function(xy){
            var t = this.activeTarget;
            if(t){
                this.urlBodyUpdate(t);
            }
        })
    });
})();


/**
 * @class Ext.form.VTypes
 * @extends Ext.form.VTypes
 */
Ext.apply(Ext.form.VTypes, {
    password : function(val, field) {
        if (field.initialPassField) {
            var pwd = Ext.getCmp(field.initialPassField);
            return (val == pwd.getValue());
        }
        return true;
    },
    passwordText : i18n.passNotMatch
});

Ext.override(Ext.ColorPalette, {
    allowReselect: true
});

Bible.getI18n = function(key){
    return (i18n[key] ? i18n[key] : key);
};
